package com.thinkfit.jy.activity;

import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.common.lib.constant.Constants;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.utils.BaseUtils;
import com.thinkfit.jy.R;
import com.thinkfit.jy.serialport.SerialPortManager;
import com.thinkfit.jy.utils.BluetoothOrder;
import com.thinkfit.jy.utils.DeviceTypeUtils;
import com.thinkfit.jy.utils.MotionDataUtils;
import com.thinkfit.jy.utils.SetTargetViewUtils;
import com.thinkfit.jy.utils.ShowSpeedViewUtils;
import com.thinkfit.jy.utils.SportsStatusBarViewUtils;
import com.thinkfit.jy.utils.ThemeUtils;
import com.thinkfit.jy.utils.Utils;
import com.thinkfit.jy.view.CCTrackView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

public class FreeMovementJyActivity extends MainActivity{

//    TrackView trackView;
//    CarTrackView trackView;
    CCTrackView trackView;
    ConstraintLayout clMain,clTop,clPb;
    TextView tvCircle,tvMeanSpeed,tvMeanPace,tvMeanStride,tvMeanStrideUnit,tvAvgStride,tvRemaining,tvRemainingUnit
            ,tvRemainingTip;
    ProgressBar pb;
    int allTime,distance;

    float allSpeed;
    float allPace;
    float allStride;
    int count = 0;
    int type,num;
    int max = 0;
    protected int getLayoutId() {
        return R.layout.activity_free_movement_new;
    }

    @Override
    public void init() {
        type = getIntent().getIntExtra(Constants.BUNDLE_EXTRA, 0);
        num = getIntent().getIntExtra(Constants.BUNDLE_EXTRA_2, 0);
        clMain = findViewById(R.id.cl_main);
        clTop = findViewById(R.id.cl_top);
        clPb = findViewById(R.id.cl_pb);
        pb = findViewById(R.id.pb);
        trackView = findViewById(R.id.trackView);

        tvCircle = findViewById(R.id.tv_circle);
        tvMeanSpeed = findViewById(R.id.tv_mean_speed);
        tvMeanPace = findViewById(R.id.tv_mean_pace);
        tvMeanStride = findViewById(R.id.tv_mean_stride);
        tvMeanStrideUnit = findViewById(R.id.tv_mean_stride_unit);
        tvAvgStride = findViewById(R.id.tv_avg_stride);
        tvRemaining = findViewById(R.id.tv_remaining);
        tvRemainingUnit = findViewById(R.id.tv_remaining_unit);
        tvRemainingTip = findViewById(R.id.tv_remaining_tip);
        resetDate();
        initView();
        if(type != 0){
            clPb.setVisibility(View.VISIBLE);
            clTop.setVisibility(View.INVISIBLE);
            if(type == SetTargetViewUtils.TYPE_TIME){
                max = num*60;
                tvRemainingUnit.setVisibility(View.GONE);
            }else if(type == SetTargetViewUtils.TYPE_DISTANCE){
                max = num*1000;
                tvRemainingUnit.setVisibility(View.VISIBLE);
                tvRemainingUnit.setText(getString(R.string.app_km));
            }else if(type == SetTargetViewUtils.TYPE_KCAL){
                max = num*10;
                tvRemainingUnit.setVisibility(View.VISIBLE);
                tvRemainingUnit.setText(getString(R.string.app_kcal));
            }
            pb.setMax(max);
        }else {
            clPb.setVisibility(View.INVISIBLE);
            clTop.setVisibility(View.VISIBLE);
        }
    }

    public void initView(){
        if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.TREADMILL)){
            tvMeanStrideUnit.setText(getString(R.string.app_spm));
            tvAvgStride.setText(getString(R.string.app_free_avg_stride));
        }else if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.SPINNING)
                || MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ELLIPTICAL_MACHINE)){
            tvMeanStrideUnit.setText(getString(R.string.app_rpm));
            tvAvgStride.setText(getString(R.string.app_free_avg_cadence));
        }else if(MotionDataUtils.mCurrentDeviceType.equals(DeviceTypeUtils.ROWING_MACHINE)){
            tvMeanStrideUnit.setText(getString(R.string.app_spm));
            tvAvgStride.setText(getString(R.string.app_free_avg_stroke));
        }
//        trackView.setVisibility(View.INVISIBLE);
    }


    @Override
    public void onResume() {
        super.onResume();
        SportsStatusBarViewUtils.getInstance().isMain(false);
        ShowSpeedViewUtils.getInstance().initView(getApplicationContext());
        clMain.setBackgroundResource(ThemeUtils.getInstance().getMainTheme());
        ShowSpeedViewUtils.getInstance().isOnClick(false);
    }

    @Override
    protected void onStop() {
        super.onStop();
        ShowSpeedViewUtils.getInstance().isOnClick(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onReceive(HashMap<String, Object> map) {
        if (map == null) {
            return;
        }
        super.onReceive(map);
        if ( map.containsKey(EventBusEvent.PAUSE_RUN)||map.containsKey(EventBusEvent.STOP_RUN)) {
            System.out.println("BluetoothOrder ------------->  STOP_RUN : 2222");
//            showStartBtn(false);
            BluetoothOrder.getInstance().uploadSportInfo(true);
            initWidget();
        }else if(map.containsKey(EventBusEvent.KILL_ACTIVITY)){
//            HashMap<String, Object> map1 = new HashMap<>();
//            map1.put(EventBusEvent.STOP_RUN,"");
//            EventBus.getDefault().post(map1);
            finish();
        }

    }

    @Override
    public void resetInfo(SerialPortManager.CurrentInfo info) {
        if(MotionDataUtils.getInstance().isRun()){

            if(allTime == info.time){
                return;
            }
            allTime = info.time;
            count ++;
            double num = Math.floor(info.distance / 400);
            long round = Math.round(num);
            if(round > 1){
                tvCircle.setText(getString(R.string.app_free_laps,round+""));
            }else {
                tvCircle.setText(getString(R.string.app_free_lap,round+""));
            }
            float speed = 0f;

            if(DeviceTypeUtils.getDeviceType() == 2){
                speed = info.speed*0.1f;
            }else {
                speed = info.speed*0.01f;
            }
            if(distance == info.distance){

            }else {
//                trackView.changeDistance(info.distance);
                trackView.setCursorPosition(info.distance);
                distance = info.distance;
            }

//            trackView1.setPosition(Float.valueOf(info.distance));
//            allSpeed = allSpeed +speed;
            float speeds = (info.distance * 1000)/ allTime;
            allSpeed = speeds*3.6f;


            if(allSpeed<=0){
                allSpeed = 0;
            }
//            allStride = allStride+(info.count/info.time)*60;

            tvMeanSpeed.setText(Utils.getNewFloat2(allSpeed/count));

            String text;
            if ((info.distance/ 1000f) <= 0) {
                text = "00:00";
            } else {
                int time = (int) (allTime /(info.distance / 1000f));  //计算好了配速   //((info.time == 0 || info.distance < 10) ? 0 : (int) (500 / (info.distance * 1.0f / info.time) + 0.5f));//计算500需要多少秒
                int hour = time / 3600;
                int minute = (time / 60) % 60;
                int second = time % 60;
                if (hour > 0) {
                    text = BaseUtils.StaticParams.getNewText(hour) + ":"
                            + BaseUtils.StaticParams.getNewText(minute) + "'"
                            + BaseUtils.StaticParams.getNewText(second)+"''";
                } else {
                    text = BaseUtils.StaticParams.getNewText(minute) + "'"
                            + BaseUtils.StaticParams.getNewText(second)+"''";
                }
            }
            if(type == SetTargetViewUtils.TYPE_TIME){
                pb.setProgress(info.time);
                tvRemaining.setText(remainNum(info.time));
            }else if(type == SetTargetViewUtils.TYPE_DISTANCE){
                pb.setProgress(info.distance);
                tvRemaining.setText(remainNum(info.distance));
            }else if(type == SetTargetViewUtils.TYPE_KCAL){
                pb.setProgress(info.kcal);
                tvRemaining.setText(remainNum(info.kcal));
            }


            tvMeanPace.setText(text);

            if(DeviceTypeUtils.getDeviceType() == 2 ||DeviceTypeUtils.getDeviceType() == 5){
                double rand = Math.random()*10;
                rand=(rand-5)*0.01+1;
                int rpm = (int) Math.ceil(speed*60/3.6*rand);
                System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaa    rpm  : "+rpm);
                tvMeanStride.setText(rpm+"");
            }else {
                tvMeanStride.setText(info.rpm+"");
            }

        }
    }



    public String remainNum(int num){
        String str = null;
        if(type == SetTargetViewUtils.TYPE_TIME){
            int time = max - num;
            if(time <= 0){
                str = getString(R.string.app_target_complete);
                tvRemainingTip.setVisibility(View.INVISIBLE);
            }else {
                int hour = time / 3600;
                int minute = (time / 60) % 60;
                int second = time % 60;
                if (hour > 0) {
                    str = BaseUtils.StaticParams.getNewText(hour) + ":"
                            + BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second);
                } else {
                    str = BaseUtils.StaticParams.getNewText(minute) + ":"
                            + BaseUtils.StaticParams.getNewText(second);
                }
            }

        }else if(type == SetTargetViewUtils.TYPE_DISTANCE){
            int distance = max - num;
            if(distance <= 0){
                str = getString(R.string.app_target_complete);
                tvRemainingTip.setVisibility(View.INVISIBLE);
            }else {
                str = Utils.getNewFloat2(distance / 1000f);
            }


        }else if(type == SetTargetViewUtils.TYPE_KCAL){
            int kcal = max - num;
            if(kcal <= 0){
                str = getString(R.string.app_target_complete);
                tvRemainingTip.setVisibility(View.INVISIBLE);
            }else {
                str = Utils.getNewFloat(kcal / 10f);
            }

        }
        return str;
    }
    public void initWidget(){
        tvMeanSpeed.setText("0.0");
        tvMeanPace.setText("0'00''");
        tvMeanStride.setText(0+"");
        tvCircle.setText(getString(R.string.app_free_lap,0+""));
        distance = 0;
    }

    public String speedKmMin(int speed){
        String text;
        if (speed <= 0) {
            text = "00’00’’";
        }else {
            int time = (int) (60 / (speed * 0.01) + 1);  //计算好了配速   //((info.time == 0 || info.distance < 10) ? 0 : (int) (500 / (info.distance * 1.0f / info.time) + 0.5f));//计算500需要多少秒
            int hour = time / 3600;
            int minute = (time / 60) % 60;
            int second = time % 60;
            if (hour > 0) {
                text = BaseUtils.StaticParams.getNewText(hour) + "’"
                        + BaseUtils.StaticParams.getNewText(minute) + "’’"
                        + BaseUtils.StaticParams.getNewText(second)+ "’’";
            } else {
                text = BaseUtils.StaticParams.getNewText(minute) + "’"
                        + BaseUtils.StaticParams.getNewText(second)+ "’’";
            }
        }
        return text;
    }
}
